<?php
/**
 * Created by PhpStorm.
 * User: CY
 * Date: 2018/3/8
 * Time: 9:20
 */

namespace app\api\model;


class Product extends BaseModel
{
    protected $autoWriteTimestamp = true;
    protected $hidden = [
        'delete_time','main_img_id','pivot','from','category_id',
        'create_time','update_time'
    ];

    /**
     * 商品图片属性
     * @return \think\model\relation\HasMany
     */
    public function imgs(){
        return $this->hasMany('ProductImage','product_id','id');
    }

    /**
     * 商品主题处理
     * @param $value
     * @param $data
     * @return string
     */
    public function getMainImgUrlAttr($value,$data){
        return $this->prefixImgUrl($value,$data);
    }

    /**
     * 关联商品特征表
     * @return \think\model\relation\HasMany
     */
    public function properties(){
        return $this->hasMany('ProductProperty','product_id','id');
    }

    /**
     * 取出所需条数的最新商品
     * @param $count
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getMostRecent($count){
        $products = self::limit($count)->order('create_time desc')->select();
        return $products;
    }

    /**
     * 获取某个分类下的商品
     * @param $categoryID
     * @param bool $paginate
     * @param int $page
     * @param int $size
     * @return false|\PDOStatement|string|\think\Collection|\think\Paginator
     */
    public static function getProductsByCategoryID($categoryID,$paginate = true,$page = 1,$size = 30){
        $query = self::where('category_id','=',$categoryID);
        if(!$paginate){ // 不分页查询
            return $query->select();
        }else{ // 分页查询
            return $query->paginate($size,true,['page' => $page]);
        }
    }

    /**
     * 获取商品详情
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getProductDetail($id){
        $product = self::with(['imgs' => function($query){
            $query->with(['imgUrl'])->order('order','asc');
        }])->with('properties')->find($id);
        return $product;
    }
}